package org.zerta.troops.core;
import org.zerta.troops.common.Area;
import org.zerta.troops.common.Army;
import org.zerta.troops.common.NormalTroop;
import org.zerta.troops.common.Player;
import org.zerta.troops.common.Unit;

import java.util.HashMap;
import java.util.Map;

public class BattleEngine {

	
	public void executeBattle(Area area, TurnProcessor turnProcessor) {
		Army ownerArmy = area.getOwnerArmy();
		Map <String, Army> currentArmies = area.getCurrentArmies();
		Map <String, Integer> playerNormalTroopArmyUnits = new HashMap<String, Integer>();
		
		Unit normalTroop = new NormalTroop();
		
		if (ownerArmy != null) {
			playerNormalTroopArmyUnits.put(ownerArmy.getOwner().getName(), new Integer(ownerArmy.getArmyUnit(normalTroop)));
		}
		for (Army attackingArmy: currentArmies.values()) {
			String lookupKey = attackingArmy.getOwner().getName();
			int oldValue = 0;
			if (playerNormalTroopArmyUnits.containsKey(lookupKey)) {
				oldValue = playerNormalTroopArmyUnits.get(lookupKey).intValue();
				playerNormalTroopArmyUnits.remove(lookupKey);
			}
			int newNormalTroops = attackingArmy.getArmyUnit(normalTroop);
			int newValue = oldValue + newNormalTroops;
			playerNormalTroopArmyUnits.put(lookupKey, new Integer(newValue));
		}
		
		int maxValue = 0;
		String winnerName = new String();
		// Run battle of all troops in playerNormalTroopsArmyUnits
		for (String ownerName: playerNormalTroopArmyUnits.keySet()) {
			int currentValue = playerNormalTroopArmyUnits.get(ownerName);
			if (currentValue > maxValue) {
				maxValue = currentValue;
				winnerName = ownerName;
			}
		}
		
		Army winnerArmy = currentArmies.get(winnerName); 
		Player winner = winnerArmy.getOwner();
		
		turnProcessor.log(winner.getName() + " won in area " + area.getName());
		
		// Cleanup
		area.clearCurrentArmies();
		area.setOwner(winner);
		area.setOwnerArmy(winnerArmy);
		winner.addAreaWithPresence(area);
		ownerArmy.getOwner().removeAreaWithPresence(area);
		
	}
}

